
import { reqGetCode, reqLogout, reqUserInfo, reqUserLogoin, reqUserRegister } from "@/api"
import { setToken, getToken, removeToken } from "@/utils/token"
const actions = {
    /* 获取验证码  获取验证码的接口把验证码返回了 但是正常情况下 后台把验证码发到用户手机上 */
    async getCode({ commit }, phone) {
        /* 把手机带给服务器 */
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit('GETCODE', result.data)
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    /* 用户注册 */
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    /* 用户登录[token] */
    async userLogin({ commit }, data) {
        let result = await reqUserLogoin(data)
        /* 服务器下发的token时用户的唯一标识 将来要使用token找服务器要用户的信息进行展示 */
        if (result.code == 200) {
            /* 用户已经登陆成功 需要持久化存储token */
            commit('USERLOGIN', result.data.token)
            /* 持久化存储token */
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'));
        }
    },
    /* 获取用户信息 */
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    /* 退出登录 */
    async userLogout({ commit }) {
        /* 只是想服务器发送请求 让服务器清除响应数据 */
        let result = await reqLogout()
        if (result.code == 200) {
            commit('CLEAR')
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }

}

const mutations = {
    /* 存储验证码 */
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    /* 清除本地数据 */
    CLEAR(state) {
        state.token = '';
        state.userInfo = {}
        removeToken()
    }
}

const getters = {

}


const state = {
    code: '',
    token: getToken(),
    userInfo: {},
}


export default {
    state,
    mutations,
    actions,
    getters,
}